package app.qrcode.browser.ykpixabay.ui.star

import android.annotation.SuppressLint
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.RecyclerView
import app.qrcode.browser.ykpixabay.R
import app.qrcode.browser.ykpixabay.logic.model.Hits
import app.qrcode.browser.ykpixabay.util.OperatePicUtil
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import kotlinx.android.synthetic.main.star_item.view.*

/**
 * Created by YiGo on 2022/4/22.
 */
class StarAdapter(private val fragment: Fragment) :
    RecyclerView.Adapter<StarAdapter.ViewHolder>() {

    val starViewModel by lazy { ViewModelProvider(fragment).get(StarViewModel::class.java) }

    var deleteObjectIdHashMap = HashMap<String, String>()

    var editState: Int = 0

    var chooseAllState: Int = 0

    private var starList = mutableListOf<Hits>()


    val viewModel by lazy { ViewModelProvider(fragment.requireActivity()).get(StarViewModel::class.java) }


    @SuppressLint("NotifyDataSetChanged")
    fun updateStarList(newList: MutableList<Hits>) {
        starList.clear()
        starList.addAll(newList)
        notifyDataSetChanged()
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val pictureStar: ImageView = view.findViewById(R.id.picture_star)
        val picTagStar: TextView = view.findViewById(R.id.picture_star_tag)
        val checkBox: CheckBox = view.findViewById(R.id.checkBox)
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.star_item, parent, false)
        val holder = ViewHolder(view)

        holder.pictureStar.setOnClickListener {
            val position = holder.absoluteAdapterPosition
            val star = starList[position]
            AlertDialog.Builder(fragment.requireContext()).apply {
                setTitle("你要保存这张图片吗")
                setPositiveButton(
                    "确定"
                ) { _, _ ->
                    OperatePicUtil.savePicByBm(context, star.webformatURL)
                }
                setNegativeButton(
                    "取消"
                ) { _, _ ->

                }
            }.create().show()
            val bundle = bundleOf("webformatURL" to star.webformatURL)
            val controller = fragment.findNavController()
            controller.navigate(R.id.action_starFragment_to_seePicFragment, bundle)
        }
        holder.checkBox.setOnCheckedChangeListener { _, bool ->
            if (chooseAllState == 0) {
                val position = holder.absoluteAdapterPosition
                val star = starList[position]
                if (bool) {
                    viewModel.querySelectedItem(star.id, deleteObjectIdHashMap)
                } else {
                    deleteObjectIdHashMap.remove(star.id)
                }
            }
        }

        return holder
    }

    fun chooseAll() {
        if (chooseAllState == 1) {
            starList.forEach {
                it.isSelected = true
            }
            deleteObjectIdHashMap.clear()
            starList.forEach {
                viewModel.querySelectedItem(it.id, deleteObjectIdHashMap)
            }
        }
    }

    fun cancelChooseAll() {
        if (chooseAllState == 0) {
            starList.forEach {
                it.isSelected = false
            }
            deleteObjectIdHashMap.clear()
        }
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val star = starList[position]
        if (chooseAllState == 1) {
            holder.checkBox.isChecked = true
        } else if (chooseAllState == 0) {
            holder.checkBox.isChecked = false
        }
        if (editState == 0) {
            holder.checkBox.visibility = View.GONE
        } else {
            holder.checkBox.visibility = View.VISIBLE
        }
        holder.picTagStar.text = star.tags
        holder.itemView.shimmerStarLayoutGallery.startShimmerAnimation()
        holder.itemView.shimmerStarLayoutText.startShimmerAnimation()
        Glide.with(holder.itemView)
            .load(star.webformatURL)
            .listener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable?,
                    model: Any?,
                    target: Target<Drawable>?,
                    dataSource: DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false.also {
                        holder.itemView.shimmerStarLayoutGallery.stopShimmerAnimation()
                        holder.itemView.shimmerStarLayoutText.stopShimmerAnimation()
                    }
                }

            })
            .placeholder(R.drawable.ic_baseline_insert_photo_24)
            .into(holder.pictureStar)
    }


    override fun getItemCount(): Int = starList.size

}